package com.lee.nio.channel;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * NIOFileChannel03
 * 使用同一ByteBuffer读写文件
 *
 * @author dralee
 * @date 2021-12-28 23:16:53
 **/
public class NIOFileChannel03 {
    public static void main(String[] args) throws IOException {

        //
        FileInputStream fileInputStream = new FileInputStream("1.txt");
        FileChannel fileChannel01 = fileInputStream.getChannel();

        FileOutputStream fileOutputStream = new FileOutputStream("2.txt");
        FileChannel fileChannel02 = fileOutputStream.getChannel();

        ByteBuffer byteBuffer = ByteBuffer.allocate(512);
        while (true) {
            // 这里有个重要操作，一定不要忘记
            /*
            public final Buffer clear() {
                position = 0;
                limit = capacity;
                mark = -1;
                return this;
            }
            * */
            byteBuffer.clear();
            int read = fileChannel01.read(byteBuffer);
            if (read == -1) {
                break;
            }
            // 将buffer数据写入到fileChannel02 --- 2.txt
            byteBuffer.flip();
            fileChannel02.write(byteBuffer);
        }
        fileChannel01.close();
        fileChannel02.close();
        fileInputStream.close();
        fileOutputStream.close();
    }
}
